﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using ZK.Common;

namespace ZK.Led
{
    public class LED
    {
        LedSdk.COMMUNICATIONINFO communicationInfo;
        List<string> listTruckInfo;
        List<string> truckInfoShow;
        private static readonly string bigScreenIP = Settings.GetAppConfig("bigScreenIP");
        private static readonly int bigScreenWidth = Settings.GetInt("bigScreenWidth");
        private static readonly int bigScreenHeight = Settings.GetInt("bigScreenHeight");
        private static readonly string titleLine = Settings.GetAppConfig("titleLine");
        private static string basePath = AppDomain.CurrentDomain.BaseDirectory;
        public LED()
        {
        }

        /// <summary>
        /// Led初始化
        /// </summary>
        /// <returns></returns>
        public bool LedSmallInitialize(string ipAddress)
        {
            Common.Log4.LogManage.WriteInfo("调用IP为" + ipAddress + "的小屏开始初始化");
            int nResult = 0;
            communicationInfo = new LedSdk.COMMUNICATIONINFO(); //定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示

            communicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
            communicationInfo.IpStr = ipAddress;//给IpStr赋值LED控制卡的IP
            communicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值
            nResult = LedSdk.LV_SetBasicInfo(ref communicationInfo, 1, MyCustomConfig.ledSmallEnterConfig.LedWidth, MyCustomConfig.ledSmallEnterConfig.LedHeight);//设置屏参，屏的颜色为2即为双基色，64为屏宽点数，32为屏高点数，具体函数参数说明见函数声明注示
            if (nResult != 0)
            {
                string errorStr = LedSdk.LS_GetError(nResult);
                Common.Log4.LogManage.WriteErr(errorStr);
                return false;
            }
            Common.Log4.LogManage.WriteInfo("调用IP为" + ipAddress + "的小屏初始化成功");
            return true;
        }

        /// <summary>
        /// 进行播放
        /// </summary>
        /// <param name="playInfo">播放内容</param>
        /// <returns></returns>
        public bool LedPaly(string ipAddress, string playInfo)
        {
            Common.Log4.LogManage.WriteInfo("调用IP为" + ipAddress + "的小屏需要显示的内容为" + playInfo);
            LedSdk.COMMUNICATIONINFO CommunicationInfo = new LedSdk.COMMUNICATIONINFO();//定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示
            CommunicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
            CommunicationInfo.IpStr = ipAddress;//给IpStr赋值LED控制卡的IP
            CommunicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值

            string errorStr = string.Empty;
            int hProgram = LedSdk.LV_CreateProgram(MyCustomConfig.ledSmallEnterConfig.LedWidth, MyCustomConfig.ledSmallEnterConfig.LedHeight, 1);//根据传的参数创建节目句柄，64是屏宽点数，32是屏高点数，2是屏的颜色，注意此处屏宽高及颜色参数必需与设置屏参的屏宽高及颜色一致，否则发送时会提示错误
            int nResult = LedSdk.LV_AddProgram(hProgram, 1, 0, 1);//添加一个节目，参数说明见函数声明注示
            if (nResult != 0)
            {
                errorStr = LedSdk.LS_GetError(nResult);
                Common.Log4.LogManage.WriteErr(errorStr);
                return false;
            }

            LedSdk.AREARECT AreaRect = new LedSdk.AREARECT();//区域坐标属性结构体变量
            AreaRect.left = 0;
            AreaRect.top = 0;
            AreaRect.width = MyCustomConfig.ledSmallEnterConfig.LedWidth;
            AreaRect.height = MyCustomConfig.ledSmallEnterConfig.LedHeight;

            LedSdk.FONTPROP FontProp = new LedSdk.FONTPROP();//文字属性
            FontProp.FontName = "宋体";
            FontProp.FontSize = 12;
            FontProp.FontColor = LedSdk.COLOR_RED;
            FontProp.FontBold = 1;
            LedSdk.PLAYPROP PlayProp = new LedSdk.PLAYPROP();
            PlayProp.InStyle = 0;
            PlayProp.DelayTime = 5;
            PlayProp.Speed = 150;
            LedSdk.LV_AddImageTextArea(hProgram, 1, 1, ref AreaRect, 0);
            //多行一屏可以显示下
            //nResult = LedSdk.LV_AddStaticTextToImageTextArea(hProgram, 1, 1, 0,
            //     playInfo, ref FontProp, 65535, 2, 1);
            //多行一屏显示不下
            nResult = LedSdk.LV_AddMultiLineTextToImageTextArea(hProgram, 1, 1, 0, playInfo, ref FontProp, ref PlayProp, 2, 1);

            nResult = LedSdk.LV_Send(ref communicationInfo, hProgram);//发送，见函数声明注示
            LedSdk.LV_DeleteProgram(hProgram);//删除节目内存对象，详见函数声明注示
            if (nResult != 0)//如果失败则可以调用LV_GetError获取中文错误信息
            {
                errorStr = LedSdk.LS_GetError(nResult);
                Common.Log4.LogManage.WriteErr(errorStr);
                return false;
            }
            Common.Log4.LogManage.WriteInfo("调用IP为" + ipAddress + "的小屏需要显示的内容为" + playInfo + "---------显示成功");
            return true;
        }

       

        public void LedBigInitialize()
        {
            int nResult;
            LedSdk.COMMUNICATIONINFO CommunicationInfo = new LedSdk.COMMUNICATIONINFO();//定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示

            CommunicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
            CommunicationInfo.IpStr = bigScreenIP;//给IpStr赋值LED控制卡的IP
            CommunicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值

            nResult = LedSdk.LV_SetBasicInfo(ref CommunicationInfo, 1, bigScreenWidth, bigScreenHeight);//设置屏参，屏的颜色为2即为双基色，64为屏宽点数，32为屏高点数，具体函数参数说明见函数声明注示
            if (nResult != 0)//如果失败则可以调用LV_GetError获取中文错误信息
            {
                string ErrStr;
                ErrStr = LedSdk.LS_GetError(nResult);
                Common.Log4.LogManage.WriteErr(ErrStr);
            }
            else
            {
                Common.Log4.LogManage.WriteInfo("大屏初始化成功");
            }
        }

        private void BigScreenShow(int EnteredCount, List<string> truckInfoShow)
        {
            try
            {
                Common.Log4.LogManage.WriteInfo("大屏展示信息------bigScreenShow----------");
                LedBigInitialize();
                int nResult;
                LedSdk.COMMUNICATIONINFO CommunicationInfo = new LedSdk.COMMUNICATIONINFO();//定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示
                CommunicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
                CommunicationInfo.IpStr = bigScreenIP;//给IpStr赋值LED控制卡的IP
                CommunicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值

                int hProgram;//节目句柄
                hProgram = LedSdk.LV_CreateProgram(bigScreenWidth, bigScreenHeight, 1);//根据传的参数创建节目句柄，64是屏宽点数，32是屏高点数，2是屏的颜色，注意此处屏宽高及颜色参数必需与设置屏参的屏宽高及颜色一致，否则发送时会提示错误
                                                                                       //此处可自行判断有未创建成功，hProgram返回NULL失败，非NULL成功,一般不会失败

                nResult = LedSdk.LV_AddProgram(hProgram, 1, 0, 1);//添加一个节目，参数说明见函数声明注示
                if (nResult != 0)
                {
                    string ErrStr;
                    ErrStr = LedSdk.LS_GetError(nResult);
                    Common.Log4.LogManage.WriteInfo(ErrStr);
                    return;
                }
                LedSdk.AREARECT AreaRect = new LedSdk.AREARECT();//区域坐标属性结构体变量
                AreaRect.left = 0;
                AreaRect.top = 0;
                AreaRect.width = bigScreenWidth;
                AreaRect.height = 16;

                LedSdk.FONTPROP FontProp = new LedSdk.FONTPROP();//文字属性
                FontProp.FontName = "宋体";
                FontProp.FontSize = 12;
                FontProp.FontColor = LedSdk.COLOR_RED;
                FontProp.FontBold = 1;
                //int nsize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(LedDll.FONTPROP));
                LedSdk.LV_AddImageTextArea(hProgram, 1, 1, ref AreaRect, 0);
                nResult = LedSdk.LV_AddStaticTextToImageTextArea(hProgram, 1, 1, 0, titleLine, ref FontProp, 65535, 2, 1);//

                //第一列
                AreaRect.left = 0;
                AreaRect.top = 16;
                AreaRect.width = bigScreenWidth / 2;
                AreaRect.height = bigScreenHeight - 32;

                FontProp.FontSize = 12;
                FontProp.FontBold = 0;
                LedSdk.LV_AddImageTextArea(hProgram, 1, 2, ref AreaRect, 0);

                nResult = LedSdk.LV_AddStaticTextToImageTextArea(hProgram, 1, 2, 1, "col1.txt", ref FontProp, 255, 0, 1);
                Common.Log4.LogManage.WriteInfo("第一列添加区域结果" + nResult);

                //第二列
                AreaRect.left += bigScreenWidth / 2;
                AreaRect.top = 16;
                AreaRect.width = bigScreenWidth / 2;
                AreaRect.height = bigScreenHeight - 32;

                FontProp.FontSize = 12;
                FontProp.FontBold = 0;
                LedSdk.LV_AddImageTextArea(hProgram, 1, 3, ref AreaRect, 0);
                LedSdk.PLAYPROP PlayProp = new LedSdk.PLAYPROP();
                PlayProp.InStyle = 0;
                PlayProp.DelayTime = 5;
                PlayProp.Speed = 150;

                nResult = LedSdk.LV_AddMultiLineTextToImageTextArea(hProgram, 1, 3, 1, "col2.txt", ref FontProp, ref PlayProp, 0, 1);
                Common.Log4.LogManage.WriteInfo("第二列添加区域结果" + nResult);

                AreaRect.left = 0;
                AreaRect.top = 112;
                AreaRect.width = bigScreenWidth;
                AreaRect.height = 16;

                FontProp.FontName = "宋体";
                FontProp.FontSize = 12;
                FontProp.FontColor = LedSdk.COLOR_RED;
                FontProp.FontBold = 1;
                //int nsize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(LedDll.FONTPROP));
                LedSdk.LV_AddImageTextArea(hProgram, 1, 4, ref AreaRect, 0);
                nResult = LedSdk.LV_AddStaticTextToImageTextArea(hProgram, 1, 4, 0, "场内车辆:" + EnteredCount, ref FontProp, 65535, 2, 1);//

                string txt = "";
                nResult = LedSdk.LV_Send(ref CommunicationInfo, hProgram);//发送，见函数声明注示
                LedSdk.LV_DeleteProgram(hProgram);//删除节目内存对象，详见函数声明注示
                if (nResult != 0)//如果失败则可以调用LV_GetError获取中文错误信息
                {
                    string ErrStr;
                    ErrStr = LedSdk.LS_GetError(nResult);
                    Common.Log4.LogManage.WriteErr(ErrStr);
                }
                else
                {
                    if (truckInfoShow != null && truckInfoShow.Count > 0)
                    {
                        for (int i = 1; i < truckInfoShow.Count + 1; i++)
                        {
                            txt += (i.ToString().PadLeft(2, '0') + " " + truckInfoShow[i - 1]) + "\r\n";
                        }
                    }
                    Common.Log4.LogManage.WriteInfo("bigScreenShow-----大屏显示信息:" + txt);
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
            }
        }

        public void BigScreenShow()
        {
            string errorStr, url, ret = string.Empty;
            string colPath1 = string.Empty;
            string colPath2 = string.Empty;
            bool b = false;
            int pageSize = 0;
            //已进厂的车辆
            int enteredCount = 0;
            listTruckInfo = new List<string>();
            truckInfoShow = new List<string>();
            try
            {
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("currentPage", "1");
                data.Add("pageSize", "1000");
                url = InterfaceExecute.GetUrl("transportProcess/getMiningAreaTruckInfo", data);
                ret = HttpClientUtil.doGetMethodToObj(url, out b);
                JObject ja = InterfaceExecute.getJobj(out errorStr, b, ret);
                if (errorStr == "" && ja != null)
                {

                    if (ja["success"] != null && bool.Parse(ja["success"].ToString()))
                    {
                        JArray ss = (JArray)ja["data"];
                        foreach (JObject item in ss)
                        {
                            listTruckInfo.Add(item["truckNo"].ToString() + "[" + item["coalName"].ToString() + "]");
                        }
                        enteredCount = listTruckInfo.Count;
                        enteredCount = 12;
                        if (enteredCount % 6 == 0)
                        {
                            pageSize = enteredCount / 6;
                        }
                        else
                        {
                            pageSize = enteredCount / 6 + 1;
                        }
                        if (listTruckInfo != null && listTruckInfo.Count > 0)
                        {
                            if (listTruckInfo.Count > 6)
                            {
                                truckInfoShow = listTruckInfo.Take(6).ToList();
                            }
                            else
                            {
                                truckInfoShow = listTruckInfo.Take(listTruckInfo.Count()).ToList();
                            }

                            listTruckInfo = listTruckInfo.Take(99).ToList();
                            colPath1 = basePath + "\\col1.txt";
                            //colPath2 = basePath + "\\col2.txt";
                            WriteTruckInfo(colPath1, listTruckInfo.Take(listTruckInfo.Count).ToList());
                            //WriteTruckInfo(colPath2, new List<string>());
                        }
                        else
                        {
                            WriteTruckInfo(colPath1, new List<string>());
                        }
                    }


                    //if (ja["success"] != null && bool.Parse(ja["success"].ToString()))
                    //{
                    //    JArray ss = (JArray)ja["data"];
                    //    foreach (JObject item in ss)
                    //    {
                    //        listTruckInfo.Add(item["truckNo"].ToString() + "[" + item["coalName"].ToString() +  "]");
                    //    }
                    //    enteredCount = listTruckInfo.Count;
                    //    if (listTruckInfo != null && listTruckInfo.Count > 0)
                    //    {
                    //        if (listTruckInfo.Count > 12)
                    //        {
                    //            truckInfoShow = listTruckInfo.Take(12).ToList();
                    //        }
                    //        else
                    //        {
                    //            truckInfoShow = listTruckInfo.Take(listTruckInfo.Count()).ToList();
                    //        }

                    //        listTruckInfo = listTruckInfo.Take(99).ToList();
                    //        colPath1 = AppDomain.CurrentDomain.BaseDirectory + "\\col1.txt";
                    //        colPath2 = AppDomain.CurrentDomain.BaseDirectory + "\\col2.txt";
                    //        if (listTruckInfo.Count <= 6)
                    //        {
                    //            WriteTruckInfo(colPath1, listTruckInfo.Take(listTruckInfo.Count).ToList());
                    //            WriteTruckInfo(colPath2, new List<string>());
                    //        }
                    //        else
                    //        {

                    //            WriteTruckInfo(colPath1, listTruckInfo.Take(6).ToList());
                    //            WriteTruckInfo(colPath2, listTruckInfo.Skip(6).Take(listTruckInfo.Count - 6).ToList());
                    //        }
                    //    }
                    //    else
                    //    {
                    //        WriteTruckInfo(colPath1, new List<string>());
                    //        WriteTruckInfo(colPath2, new List<string>());
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.Message);
            }
            BigScreenShow(enteredCount, truckInfoShow);
        }

        private void WriteTruckInfo(string path, List<string> truckInfoList)
        {
            //var b = from t in truckInfoList select t;
            //Common.Log4.LogManage.WriteInfo("路径" + path + "收到的数据是:" + b.ToArray());
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (FileStream fs = new FileStream(path, FileMode.CreateNew))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))//转码
                    {
                        if (truckInfoList.Count > 0)
                        {
                            //int count = 0;
                            //if (path.Contains("col2.txt"))
                            //{
                            //    count = 6;
                            //}

                            for (int i = 1; i < truckInfoList.Count + 1; i++)
                            {
                                //sw.WriteLine(((i + count).ToString().PadLeft(2, '0') + " " + truckInfoList[i - 1]));
                                sw.WriteLine(truckInfoList[i - 1]);
                            }
                        }
                    }
                }
                Common.Log4.LogManage.WriteInfo("地址" + path + "写入的内容为:" + ReadTextContext(path));
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
            }
        }

        private string ReadTextContext(string filePath)
        {
            string strData = "";
            try
            {
                string line;
                // 创建一个 StreamReader 的实例来读取文件 ,using 语句也能关闭 StreamReader
                using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
                {
                    // 从文件读取并显示行，直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        strData += line;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return strData;
        }
    }
    //public class LedParameter
    //{
    //    public int SendType { get; set; }
    //    public string IpStr { get; set; }
    //    public int LedNumber { get; set; }
    //    public int ColorType { get; set; }
    //    public int LedWidth { get; set; }
    //    public int LedHeight { get; set; }
    //}
}
